package com.example.hotelapp.Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.icu.util.Calendar;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.example.hotelapp.Activity.SelectActivity;
import com.example.hotelapp.Adapter.HomeAdapter;
import com.example.hotelapp.Base.BaseFragment;
import com.example.hotelapp.Bean.HomeIndexBean;
import com.example.hotelapp.R;
import com.example.hotelapp.Utils.AppNetConfig;
import com.example.hotelapp.Utils.MyApp;
import com.example.utils.Utils.DYLoadingView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.TaurusHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.example.hotelapp.Utils.MyCommonUtils.*;
import static com.example.utils.CommonUtils.*;

public class HomeFragment extends BaseFragment {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.dizhi)
    EditText dizhi;
    @BindView(R.id.start)
    TextView start;
    @BindView(R.id.dao)
    TextView dao;
    @BindView(R.id.end)
    TextView end;
    @BindView(R.id.level)
    EditText level;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loading)
    DYLoadingView loading;

    private List<String> mTitleList = new ArrayList<>();
    private List<String> mImgList = new ArrayList<>();
    private HomeAdapter homeAdapter;
    private Activity activity;
    private MediaPlayer mRingPlayer;

    /**
     * 加载布局
     */
    @Override
    protected int setLayoutId() {
        return R.layout.fragment_home;
    }

    /**
     * 初始化
     */
    @Override
    protected void init() {
        activity = getActivity();
        initHomeView();
        //刷新
        refreshLayout.setRefreshHeader(new TaurusHeader(activity));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initHomeView();
                HttpProxyCacheServer proxy = MyApp.getProxy(activity);
                String proxyUrl = proxy.getProxyUrl(AppNetConfig.RefrashMusicUrl);
                mRingPlayer = MediaPlayer.create(activity, Uri.parse(proxyUrl));
                mRingPlayer.setLooping(false);
                mRingPlayer.start();
                refreshLayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        //轮播图
        mImgList.add(AppNetConfig.HotelImgUrl + "jiudian1.jpeg");
        mImgList.add(AppNetConfig.HotelImgUrl + "jiudian2.jpg");
        mImgList.add(AppNetConfig.HotelImgUrl + "jiudian3.jpeg");

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //  banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE); // 显示圆形指示器和标题（水平显示
        //设置图片加载器
        banner.setImageLoader(new MyLoader());
        //设置图片集合
        banner.setImages(mImgList);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当banner样式有显示title时）
        banner.setBannerTitles(mTitleList);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    //图片加载器
    public class MyLoader extends ImageLoader {
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    }

    /**
     * 加载首页信息
     */
    private void initHomeView() {
        loading.start();
        loading.setVisibility(View.VISIBLE);
        OKPostNovalue( AppNetConfig.SelecthomeIndexView, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                loading.stop();
                loading.setVisibility(View.GONE);
                 activity.runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         ToastShow(activity,"服务器出错，请稍后再试");
                     }
                 });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //获取返回的json数据并解析
                String json = response.body().string();
                System.out.println(json);
                HomeIndexBean databean = new Gson().fromJson(json, HomeIndexBean.class);
                int code = databean.getCode();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loading.stop();
                        loading.setVisibility(View.GONE);
                        if (code == 1) {
                            //请求成功
                            recyclerView.setLayoutManager(new GridLayoutManager(activity, 1));
                            homeAdapter = new HomeAdapter(activity, databean.getData());
                            recyclerView.setAdapter(homeAdapter);
                        } else {
                            ToastShow(activity,"数据加载失败");
                            recyclerView.setAdapter(null);
                        }
                    }
                });
            }
        });

    }


    /**
     * 点击事件
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.start, R.id.end, R.id.sousuo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start:
                SelectTime(start,1);
                break;
            case R.id.end:
                SelectTime(end,2);
                break;
            case R.id.sousuo:
                SelectHotel();
                break;
        }
    }

    /**
     * 搜索
     */
    private void SelectHotel() {
        String address = dizhi.getText().toString().trim();
        String levels =  level.getText().toString().trim();
        if (address.isEmpty()){
            ToastShow(activity,"请输入地址");
        }else {
            SelectActivity.start(activity,address,levels);
        }

    }

    /**
     * 选择时间
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void SelectTime(TextView timemark,int mark) {
        Calendar mcalendar = Calendar.getInstance(Locale.CHINA);
        int year = mcalendar.get(Calendar.YEAR);         //  得到当前年
        int month = mcalendar.get(Calendar.MONTH);       //  得到当前月
        int day = mcalendar.get(Calendar.DAY_OF_MONTH);  //  得到当前日

        new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {      //  日期选择对话框
            @SuppressLint("SetTextI18n")
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                int month2 = month + 1; //因为当前会减一
                String m = String.valueOf(month2);
                String d = String.valueOf(dayOfMonth);
                if (month2 < 10){
                    m = "0" + month2;
                }
                if (dayOfMonth < 10){
                    d = "0" + dayOfMonth;
                }
                if (mark == 1){
                    timemark.setText(m + "月" + d + "日");
                }else if (mark == 2){
                    timemark.setText(m + "月" + d + "日");
                }
            }
        }, year, month, day).show();   //  弹出日历对话框时，默认显示 年，月，日
    }

}
